// 判断是否为Safari浏览器
export const isSafari = (): boolean => {
  if (typeof navigator === 'undefined') return false;
  const ua = navigator.userAgent.toLowerCase();
  return ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1 && ua.indexOf('android') === -1;
};

// Cookie操作函数
export const setCookie = (name: string, value: string, days = 7): void => {
  if (typeof document === 'undefined') return;
  const date = new Date();
  date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  const expires = "; expires=" + date.toUTCString();
  document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/; SameSite=Lax";
};

export const getCookie = (name: string): string | null => {
  if (typeof document === 'undefined') return null;
  const nameEQ = name + "=";
  const ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
  }
  return null;
};

export const deleteCookie = (name: string): void => {
  if (typeof document === 'undefined') return;
  document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};

// 统一的存储操作函数
export const setStorageItem = (key: string, value: string): void => {
  if (isSafari()) {
    setCookie(key, value);
    return;
  }

  try {
    if (typeof localStorage !== 'undefined') {
      localStorage.setItem(key, value);
    }
  } catch (e) {
    console.warn(`localStorage存储失败，回退到cookie: ${key}`, e);
    setCookie(key, value);
  }
};

export const getStorageItem = (key: string): string | null => {
  if (isSafari()) {
    return getCookie(key);
  }

  try {
    if (typeof localStorage !== 'undefined') {
      const value = localStorage.getItem(key);
      if (value) return value;
    }
  } catch (e) {
    console.warn(`localStorage读取失败，尝试cookie: ${key}`, e);
  }
  
  // 尝试从cookie读取
  return getCookie(key);
};

export const removeStorageItem = (key: string): void => {
  if (isSafari()) {
    deleteCookie(key);
    return;
  }

  try {
    if (typeof localStorage !== 'undefined') {
      localStorage.removeItem(key);
    }
  } catch (e) {
    console.warn(`localStorage删除失败: ${key}`, e);
  }
  
  // 同时确保cookie也被删除
  deleteCookie(key);
}; 